package com.dl.mall.exception;

import cn.dev33.satoken.exception.DisableLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import cn.dev33.satoken.util.SaResult;
import com.dl.mall.utils.result.Result;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * SaToken其他异常
 * @author DL
 * @create 2022-04-07 10:49
 */
@Order(value = Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class GlobalSaTokenException {

    @ResponseBody
    @ExceptionHandler(value = {NotRoleException.class, NotPermissionException.class, DisableLoginException.class})
    public Result handlerException(Exception e, HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        // 打印堆栈，以供调试
        System.out.println("SaToken其他异常---------------");
        e.printStackTrace();

        // 不同异常返回不同状态码
        String message = "";
        if(e instanceof NotRoleException) {		// 如果是角色异常
            NotRoleException ee = (NotRoleException) e;
            message = "无此角色：" + ee.getRole();
        }
        else if(e instanceof NotPermissionException) {	// 如果是权限异常
            NotPermissionException ee = (NotPermissionException) e;
            message = "无此权限：" + ee.getCode();
        }
        else if(e instanceof DisableLoginException) {	// 如果是被封禁异常
            DisableLoginException ee = (DisableLoginException) e;
            message = "账号被封禁：" + ee.getDisableTime() + "秒后解封";
        }
        else {	// 普通异常, 输出：500 + 异常信息
            message = e.getMessage();
        }

        // 返回给前端
        return Result.error(message);
    }

}
